import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/primary_button.dart';

import 'package:casdon/modules/lifeCircle/application/notification/life_self_topic_list_notifier.dart';

import 'package:casdon/modules/lifeCircle/ui/widgets/topic_item_widget.dart';
import 'package:casdon/modules/me/application/notification/user_center_notifier.dart';
import 'package:casdon/modules/me/application/notification/user_info_notifier.dart';
import 'package:casdon/modules/me/data/model/user_center_model.dart';
import 'package:casdon/modules/me/data/model/user_info_model.dart';
import 'package:casdon/modules/me/ui/widgets/circle_avatar_button.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 自己的生活圈主页
@RoutePage()
class LifeSelfHomeScreen extends ConsumerStatefulWidget {
  const LifeSelfHomeScreen({super.key});

  @override
  ConsumerState<LifeSelfHomeScreen> createState() => _LifeSelfHomeScreenState();
}

class _LifeSelfHomeScreenState extends ConsumerState<LifeSelfHomeScreen> {
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final userCenter = ref.read(userCenterNotifierProvider.notifier);
      userCenter.fetchData();

      final userInfo = ref.read(userInfoNotifierProvider.notifier);
      userInfo.fetchData();
    });

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final userInfoState = ref.watch(userInfoNotifierProvider);
    final userCenterState = ref.watch(userCenterNotifierProvider);
    final selfTopicState = ref.watch(lifeSelfTopicListNotifierProvider);
    final selfTopicNotifier = ref.watch(
      lifeSelfTopicListNotifierProvider.notifier,
    );

    return Scaffold(
      backgroundColor: context.colorScheme.surface, // 设置页面背景色
      body: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollEndNotification &&
              notification.metrics.pixels >=
                  notification.metrics.maxScrollExtent - 50) {
            selfTopicNotifier.loadMore();
          }
          return false;
        },
        child: RefreshIndicator(
          onRefresh: () async {
            selfTopicNotifier.refresh();
          },
          child: CustomScrollView(
            slivers: [
              /// 顶部紫色区域
              SliverPersistentHeader(
                pinned: true,
                delegate: _BrandHeaderDelegate(
                  userCenter: userCenterState,
                  userInfo: userInfoState,
                  topicTotalSize: selfTopicState.when(
                    data: (data) => data.totalSize,
                    loading: () => 0,
                    error: (e, st) => 0,
                  ),
                  ref: ref,
                ),
              ),

              /// 动态列表
              selfTopicState.when(
                loading: () => SliverToBoxAdapter(
                  child: Center(child: CircularProgressIndicator()),
                ),
                error: (error, stackTrace) =>
                    SliverToBoxAdapter(child: Center(child: Text(''))),
                data: (state) {
                  final items = state.data ?? [];
                  if (items.isEmpty) {
                    return SliverToBoxAdapter(
                      child: Padding(
                        padding: EdgeInsets.only(top: 60.h),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Image.asset(
                              Assets.images.emptyData.path,
                              width: 120.w,
                              height: 80.h,
                            ),
                            SizedBox(height: 12.h),
                            Text(
                              '还没有发帖',
                              style: TextStyle(color: Colors.grey.shade500),
                            ),
                            SizedBox(height: 12.h),
                            PrimaryButton(
                              text: '去发帖',
                              width: 95.w,
                              height: 32.h,
                              onPressed: () => context.router.push(
                                const LifeCreatePostRoute(),
                              ),
                            ),
                          ],
                        ),
                      ),
                    );
                  }
                  return SliverList(
                    delegate: SliverChildBuilderDelegate(
                      (context, index) => TopicItemWidget(
                        topic: items[index],
                        showFollowBtn:
                            items[index].isFollow == false &&
                            items[index].isMyTopic == false,
                      ),
                      childCount: items.length,
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

/// ---------- Header ----------
class _BrandHeaderDelegate extends SliverPersistentHeaderDelegate {
  final double _height = 242.h;
  final UserCenterModel userCenter;
  final UserInfoModel userInfo;
  final int topicTotalSize;
  final WidgetRef ref;

  _BrandHeaderDelegate({
    required this.userCenter,
    required this.userInfo,
    required this.topicTotalSize,
    required this.ref,
  });

  @override
  double get maxExtent => _height;
  @override
  double get minExtent => _height;

  @override
  Widget build(
    BuildContext context,
    double shrinkOffset,
    bool overlapsContent,
  ) {
    return Container(
      decoration: const BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.centerLeft, // 左边开始
          end: Alignment.centerRight, // 右边结束
          colors: [
            Color(0xFF9470FF), // 起始颜色
            Color(0xFF6652F9), // 结束颜色
          ],
        ),
      ),
      child: SafeArea(
        bottom: false,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.only(left: 12.w, right: 12.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    height: 48.h,
                    alignment: Alignment.centerLeft,
                    child: Row(
                      children: [
                        IconButton(
                          icon: const Icon(
                            Icons.arrow_back_ios,
                            color: Colors.white,
                          ),
                          onPressed: () => Navigator.pop(context),
                        ),
                        const Spacer(),

                        TextButton(
                          onPressed: () => _handleEditInfo(context),
                          child: Text(
                            "编辑资料",
                            style: context.textTheme.headlineMedium!.copyWith(
                              color: Colors.white,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 24.h),
                  Row(
                    children: [
                      SizedBox(width: 12.w),
                      CircleAvatarButton(
                        imageUrl: userInfo.userAvatars,
                        defaultImage: AssetImage(Assets.images.icAvatar.path),
                        size: 48.w,
                        onPressed: () => _handleAvatarClick(context),
                      ),
                      SizedBox(width: 12.w),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              (userInfo.nickName ?? "").isEmpty
                                  ? "凯度生活家"
                                  : userInfo.nickName!,
                              style: context.textTheme.headlineLarge!.copyWith(
                                color: Colors.white,
                              ),
                              overflow: TextOverflow.ellipsis,
                            ),
                            SizedBox(height: 10.h),
                            Row(
                              children: [
                                Text(
                                  "${userCenter.fansTotal}",
                                  style: context.textTheme.bodyLarge!.copyWith(
                                    color: Colors.white,
                                  ),
                                ),
                                Text(
                                  " 粉丝",
                                  style: context.textTheme.bodyMedium!.copyWith(
                                    color: Colors.white,
                                  ),
                                ),
                                SizedBox(width: 25.w),
                                Text(
                                  "${userCenter.followTotal}",
                                  style: context.textTheme.bodyLarge!.copyWith(
                                    color: Colors.white,
                                  ),
                                ),
                                Text(
                                  " 关注",
                                  style: context.textTheme.bodyMedium!.copyWith(
                                    color: Colors.white,
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            const Spacer(),
            Container(
              padding: EdgeInsets.only(left: 16.w),
              width: double.infinity,
              height: 47.h,
              alignment: Alignment.centerLeft,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(12),
                  topRight: Radius.circular(12),
                ),
                border: const Border(
                  bottom: BorderSide(color: Color(0xFFF0F0F0)),
                ),
              ),
              child: Text(
                "全部动态 ($topicTotalSize)",
                style: context.textTheme.bodyMedium!.copyWith(
                  color: context.customColorThemeNonNull.textColor1,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  bool shouldRebuild(covariant _BrandHeaderDelegate oldDelegate) =>
      oldDelegate.userInfo != userInfo ||
      oldDelegate.topicTotalSize != topicTotalSize;

  void _handleAvatarClick(BuildContext context) {}

  void _handleEditInfo(BuildContext context) {
    context.router.push(const MeInfoRoute());
  }
}
